package com.mall.page.web.service.impl;

import com.mall.common.util.RespResult;
import com.mall.page.web.service.ISeckillPageService;
import com.mall.seckill.feign.SeckillGoodsFeign;
import com.mall.seckill.model.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author Darren
 * @date 2022-08-26 10:44
 * Description：
 */
@Service
public class SeckillPageServiceImpl implements ISeckillPageService {
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private SeckillGoodsFeign seckillGoodsFeign;

    @Value("${seckill-path}")
    private String seckillPath;

    @Override
    public void generateHtml(String id) throws FileNotFoundException, UnsupportedEncodingException {
        // 1、创建Thymeleaf容器对象
        Context context = new Context();
        // 2、设置页面数据模型
        context.setVariables(dataLoad(id));
        // 3、创建文件
        File file = new File(seckillPath, id + ".html");
        PrintWriter writer = new PrintWriter(file, "UTF-8");
        // 4、生成页面
        templateEngine.process("seckill", context, writer);
    }

    @Override
    public void deleteHtml(String id) {
        File file = new File(seckillPath, id + ".html");
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 数据加载
     *
     * @param id
     * @return
     */
    private Map<String, Object> dataLoad(String id) {
        RespResult<SeckillGoods> seckillGoodsRespResult = seckillGoodsFeign.getById(id);
        if (seckillGoodsRespResult.getData() != null) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("item", seckillGoodsRespResult.getData());
            dataMap.put("images", seckillGoodsRespResult.getData().getImages().split(","));
            return dataMap;
        }
        return null;
    }
}
